package cn.qiyu5522.controller;


import cn.qiyu5522.domain.DTO.CategoryPageQueryDTO;
import cn.qiyu5522.domain.VO.ExcelCategoryVo;
import cn.qiyu5522.domain.entity.Category;
import cn.qiyu5522.domain.entity.ResponseResult;
import cn.qiyu5522.enums.AppHttpCodeEnum;
import cn.qiyu5522.service.CategoryService;
import cn.qiyu5522.utils.BeanCopyUtils;
import cn.qiyu5522.utils.WebUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 分类表 前端控制器
 * </p>
 *
 * @author Tonkey
 * @since 2024-04-24
 */
@RestController
@RequestMapping("/content/category")
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    @GetMapping("/listAllCategory")
    public ResponseResult listAllCategory(){
        return categoryService.listAllCategory();
    }


    @PreAuthorize("@ps.hasPermission('content:category:list')")
    @GetMapping("list")
    public ResponseResult list(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam( required = false) String name,
                               // 未来可能加入的查询条件
                               @RequestParam( required = false) String status){
        CategoryPageQueryDTO categoryPageQueryDTO = new CategoryPageQueryDTO(pageNum, pageSize, name, status);
        return categoryService.getCategoryListByCondition(categoryPageQueryDTO);
    }


    @PreAuthorize("@ps.hasPermission('content:category:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            // 设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类.xlsx",response);
            // 获取需要导出的数据
            List<Category> categoryVOs = categoryService.list();
            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryVOs, ExcelCategoryVo.class);

            // 把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(),ExcelCategoryVo.class)
                    // 自动列宽
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("分类导出")
                    .doWrite(excelCategoryVos);
        } catch (Exception e) {
            // 如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }

}
